<template>
  <div class="browse-tasks-wrapper">
    <div class="browse-tasks-container">
      <div class="browse-tasks-header">
        <h1>浏览任务</h1>
        <p>查看所有可接取的任务</p>
      </div>

      <div class="tasks-filter">
        <input 
          type="text" 
          v-model="searchKeyword" 
          placeholder="搜索任务标题或描述..." 
          class="search-input"
        />
        <button @click="fetchTasks" class="search-button">搜索</button>
      </div>

      <div v-if="loading" class="loading">加载中...</div>
      
      <div v-else-if="tasks.length === 0" class="no-tasks">
        <p>暂无任务</p>
      </div>
      
      <div v-else class="tasks-list">
        <div 
          v-for="task in tasks" 
          :key="task.taskId" 
          class="task-card"
          @click="showTaskDetail(task)"
        >
          <div class="task-header">
            <h3>{{ task.title }}</h3>
            <span :class="['status-badge', getStatusClass(task.status)]">
              {{ getStatusText(task.status) }}
            </span>
          </div>
          
          <div class="task-content">
            <div class="task-meta">
              <div class="meta-item">
                <span class="meta-label">预算:</span>
                <span class="meta-value">¥{{ task.budget }}</span>
              </div>
              <div class="meta-item">
                <span class="meta-label">发布者:</span>
                <span class="meta-value">{{ task.employerName }}</span>
              </div>
              <div class="meta-item">
                <span class="meta-label">发布日期:</span>
                <span class="meta-value">{{ formatDate(task.publishDate) }}</span>
              </div>
            </div>
          </div>
          
          <div class="task-actions">
            <button 
              v-if="task.status === 0" 
              @click.stop="acceptTask(task.taskId)"
              class="accept-button"
            >
              接取任务
            </button>
            <button 
              v-else 
              disabled 
              class="accept-button disabled"
            >
              {{ getStatusText(task.status) }}
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 自定义弹窗 -->
    <MessageModal 
      :visible="modalVisible"
      :title="modalTitle"
      :message="modalMessage"
      :type="modalType"
      @close="closeModal"
      @confirm="handleModalConfirm"
    />
    
    <!-- 任务详情弹窗 -->
    <div v-if="detailModalVisible" class="task-detail-modal-overlay" @click="closeDetailModal">
      <div class="task-detail-modal-container" @click.stop>
        <div class="task-detail-modal-header">
          <h2>{{ selectedTaskDetail.task?.title }}</h2>
          <button class="task-detail-modal-close" @click="closeDetailModal">&times;</button>
        </div>
        <div class="task-detail-modal-body">
          <div class="task-detail-section">
            <div class="task-detail-row">
              <label>任务状态:</label>
              <span :class="['status-badge', getStatusClass(selectedTaskDetail.task?.status)]">
                {{ getStatusText(selectedTaskDetail.task?.status) }}
              </span>
            </div>
            
            <div class="task-detail-row">
              <label>发布者:</label>
              <span>{{ selectedTaskDetail.task?.employerName }}</span>
            </div>
            
            <div class="task-detail-row">
              <label>预算:</label>
              <span class="budget">¥{{ selectedTaskDetail.task?.budget }}</span>
            </div>
            
            <div class="task-detail-row">
              <label>发布日期:</label>
              <span>{{ formatDate(selectedTaskDetail.task?.publishDate) }}</span>
            </div>
            
            <div class="task-detail-row description-row">
              <label>任务描述:</label>
              <div class="task-description">{{ selectedTaskDetail.task?.description }}</div>
            </div>
            
            <!-- 任务评价部分 -->
            <div v-if="selectedTaskDetail.evaluation" class="task-detail-row evaluation-section">
              <label>任务评价:</label>
              <div class="evaluation-content">
                <div class="evaluation-header">
                  <div class="rating">
                    <span 
                      v-for="i in 5" 
                      :key="i" 
                      class="star" 
                      :class="{ 'filled': i <= selectedTaskDetail.evaluation.score }"
                    >
                      ★
                    </span>
                  </div>
                  <div class="evaluation-time">
                    {{ formatDate(selectedTaskDetail.evaluation.evaluationTime) }}
                  </div>
                </div>
                <div class="evaluation-text">
                  {{ selectedTaskDetail.evaluation.content }}
                </div>
              </div>
            </div>
            
            <div v-else class="task-detail-row evaluation-section">
              <label>任务评价:</label>
              <div class="no-evaluation">暂无评价</div>
            </div>
          </div>
        </div>
        <div class="task-detail-modal-footer">
          <button class="modal-button" @click="closeDetailModal">关闭</button>
          <button 
            v-if="showAcceptButton && selectedTaskDetail.task?.status === 0" 
            class="modal-button accept-button"
            @click="acceptTask(selectedTaskDetail.task?.taskId)"
          >
            接取任务
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import api from '../api/index.js'
import MessageModal from './MessageModal.vue'

const router = useRouter()
const tasks = ref([])
const loading = ref(false)
const searchKeyword = ref('')

// 弹窗相关状态
const modalVisible = ref(false)
const detailModalVisible = ref(false)
const selectedTaskDetail = ref({
  task: {},
  evaluation: null
})
const modalTitle = ref('')
const modalMessage = ref('')
const modalType = ref('info')
const successCallback = ref(null)
const showAcceptButton = ref(true)

// 显示弹窗
const showModal = (title, message, type = 'info', callback = null) => {
  modalTitle.value = title
  modalMessage.value = message
  modalType.value = type
  modalVisible.value = true
  successCallback.value = callback
}

// 关闭弹窗
const closeModal = () => {
  modalVisible.value = false
}

// 显示详情弹窗
const showTaskDetail = async (task) => {
  try {
    // 获取任务详情及评价
    const response = await api.get(`/task/detail-with-evaluation/${task.taskId}`)
    if (response.code === 0) {
      selectedTaskDetail.value = response.data
      detailModalVisible.value = true
    } else {
      showModal('错误', '获取任务详情失败: ' + response.message, 'error')
    }
  } catch (error) {
    console.error('获取任务详情失败:', error)
    showModal('错误', '获取任务详情失败，请重试', 'error')
  }
}

// 关闭详情弹窗
const closeDetailModal = () => {
  detailModalVisible.value = false
}

// 处理弹窗确认
const handleModalConfirm = () => {
  if (successCallback.value) {
    successCallback.value()
  }
}

// 获取状态文本
const getStatusText = (statusCode) => {
  const statusMap = {
    0: '待接取',
    1: '进行中',
    2: '已完成',
    3: '已关闭'
  }
  return statusMap[statusCode] || '未知状态'
}

// 获取状态样式类
const getStatusClass = (statusCode) => {
  const classMap = {
    0: 'pending',
    1: 'in-progress',
    2: 'completed',
    3: 'closed'
  }
  return classMap[statusCode] || 'unknown'
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 获取所有任务
const fetchTasks = async () => {
  loading.value = true
  try {
    const response = await api.get('/task/all')
    if (response.code === 0) {
      tasks.value = response.data
    } else {
      showModal('错误', '获取任务列表失败: ' + response.message, 'error')
    }
  } catch (error) {
    console.error('获取任务列表失败:', error)
    showModal('错误', '获取任务列表失败，请重试', 'error')
  } finally {
    loading.value = false
  }
}

// 接取任务
const acceptTask = async (taskId) => {
  try {
    const response = await api.post(`/task/accept/${taskId}`)
    if (response.code === 0) {
      showModal('成功', '任务接取成功！', 'success')
      
      // 更新任务状态为进行中
      const task = tasks.value.find(t => t.taskId === taskId)
      if (task) {
        task.status = 1 // 进行中
      }
      
      // 关闭详情弹窗
      closeDetailModal()
    } else {
      showModal('错误', '接取任务失败: ' + response.message, 'error')
    }
  } catch (error) {
    console.error('接取任务失败:', error)
    showModal('错误', '接取任务失败，请重试', 'error')
  }
}

onMounted(() => {
  fetchTasks()
})
</script>

<style scoped>
.browse-tasks-wrapper {
  min-height: 100vh;
  width: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  box-sizing: border-box;
  position: relative;
}

.browse-tasks-container {
  width: 100%;
  max-width: none;
  min-height: calc(100vh - 40px);
  background: white;
  border-radius: 12px;
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
  padding: 30px;
  margin: 0 auto;
  box-sizing: border-box;
}

.browse-tasks-header {
  text-align: center;
  margin-bottom: 30px;
}

.browse-tasks-header h1 {
  color: #333;
  font-size: 32px;
  margin-bottom: 10px;
  font-weight: 700;
}

.browse-tasks-header p {
  color: #666;
  font-size: 18px;
}

.tasks-filter {
  display: flex;
  gap: 15px;
  margin-bottom: 30px;
  align-items: center;
}

.search-input {
  flex: 1;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 16px;
  transition: border-color 0.3s;
  box-sizing: border-box;
}

.search-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

.search-button {
  padding: 12px 25px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.search-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}

.loading, .no-tasks {
  text-align: center;
  padding: 40px 0;
  color: #666;
  font-size: 18px;
}

.tasks-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 25px;
}

.task-card {
  border: 1px solid #eee;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);
  transition: transform 0.3s, box-shadow 0.3s;
  background: #fff;
  cursor: pointer;
}

.task-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.task-header h3 {
  color: #333;
  font-size: 20px;
  margin: 0;
  flex: 1;
  margin-right: 10px;
}

.status-badge {
  padding: 5px 10px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  white-space: nowrap;
}

.status-badge.pending {
  background-color: #fff3cd;
  color: #856404;
}

.status-badge.in-progress {
  background-color: #cce5ff;
  color: #004085;
}

.status-badge.completed {
  background-color: #d4edda;
  color: #155724;
}

.status-badge.closed {
  background-color: #f8d7da;
  color: #721c24;
}

.task-content {
  margin-bottom: 20px;
}

.task-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.meta-item {
  display: flex;
  gap: 5px;
}

.meta-label {
  font-weight: 600;
  color: #333;
}

.meta-value {
  color: #666;
}

.task-actions {
  border-top: 1px solid #eee;
  padding-top: 15px;
}

.accept-button {
  width: 100%;
  padding: 12px;
  background: linear-gradient(135deg, #28a745 0%, #238b3c 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.accept-button:hover:not(.disabled) {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(40, 167, 69, 0.4);
}

.accept-button.disabled {
  background: #ccc;
  cursor: not-allowed;
}

/* 任务详情弹窗样式 */
.task-detail-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.task-detail-modal-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow: hidden;
  animation: modalFadeIn 0.3s ease-out;
}

@keyframes modalFadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.task-detail-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 25px;
  border-bottom: 1px solid #eee;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.task-detail-modal-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.task-detail-modal-close {
  background: none;
  border: none;
  font-size: 28px;
  cursor: pointer;
  color: white;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.task-detail-modal-close:hover {
  color: #f0f0f0;
}

.task-detail-modal-body {
  padding: 25px;
  max-height: 60vh;
  overflow-y: auto;
}

.task-detail-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.task-detail-row {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.task-detail-row:last-child {
  border-bottom: none;
}

.task-detail-row label {
  font-weight: 600;
  color: #333;
  min-width: 80px;
  flex-shrink: 0;
}

.task-detail-row .status-badge {
  font-size: 14px;
  padding: 6px 12px;
}

.task-detail-row .budget {
  font-size: 20px;
  font-weight: 700;
  color: #43e97b;
}

.task-description {
  color: #666;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
}

.evaluation-section {
  flex-direction: column;
  align-items: flex-start;
}

.evaluation-content {
  flex: 1;
  width: 100%;
}

.evaluation-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.rating {
  display: flex;
  gap: 2px;
}

.star {
  color: #ddd;
  font-size: 18px;
}

.star.filled {
  color: #ffc107;
}

.evaluation-time {
  color: #999;
  font-size: 14px;
}

.evaluation-text {
  color: #666;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
}

.no-evaluation {
  color: #999;
  font-style: italic;
}

.task-detail-modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 15px 25px;
  border-top: 1px solid #eee;
  background: #f8f9fa;
}

.modal-button {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.modal-button {
  background-color: #6c757d;
  color: white;
}

.modal-button:hover {
  background-color: #5a6268;
  transform: translateY(-2px);
}

.modal-button.accept-button {
  background: linear-gradient(135deg, #28a745 0%, #238b3c 100%);
  color: white;
}

.modal-button.accept-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(40, 167, 69, 0.4);
}

@media (max-width: 768px) {
  .browse-tasks-wrapper {
    padding: 15px;
  }
  
  .browse-tasks-container {
    padding: 20px;
  }
  
  .browse-tasks-header h1 {
    font-size: 28px;
  }
  
  .browse-tasks-header p {
    font-size: 16px;
  }
  
  .tasks-filter {
    flex-direction: column;
  }
  
  .tasks-list {
    grid-template-columns: 1fr;
  }
  
  .task-detail-modal-container {
    width: 95%;
  }
  
  .task-detail-modal-header {
    padding: 15px 20px;
  }
  
  .task-detail-modal-header h2 {
    font-size: 20px;
  }
  
  .task-detail-modal-body {
    padding: 20px;
  }
  
  .task-detail-row {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .task-detail-row label {
    margin-bottom: 5px;
  }
}
</style>